import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { requestType } from '@/api/modules/model'
import { getToken } from './token'
import { useUserStore } from '@/store'
const userStore = useUserStore()

const handleCode = async (code: number, msg: string) => {
  console.log(code, msg, 'code, msg')
  switch (code) {
    case 401:
      showFailToast(msg || '登录失效')
      setTimeout(() => {
        console.log('登录失效')
      }, 1500)
      // 跳转登录
      userStore.logout()
      break
    default:
      showFailToast(msg || `后端接口${code}异常`)
      break
  }
}

// 创建axsio 赋给常量service
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL,
  timeout: 30000,
  headers: {
    // 'Content-Type': 'application/json;charset=UTF-8'
  }
})
// 添加请求拦截器
service.interceptors.request.use(
  (config: any) => {
    console.log(config, 'config')

    // 设置token到请求头
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }

    return config
  },
  (error: any) => {
    // 对请求错误做些什么
    console.log(error, 'error')
    return Promise.reject(error)
  }
)
// 添加响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    // response参数是响应对象
    // 对响应数据做点什么
    const { data: _data, config: _config } = response

    // 待添加请求失败重试
    console.log(response, 'error')
    // return response
    return _data
  },
  (error: any) => {
    const { response } = error || {}

    // 待添加请求失败重试
    console.log(error, 'error')
    if (response && response.data) {
      const { status = 500, data } = response

      handleCode(status, data.msg || data.error)

      // 对响应错误做点什么
      return Promise.reject(error)
    } else {
      let { message } = error
      if (message === 'Network Error') {
        message = '后端接口连接异常'
      }
      if (message.includes('timeout')) {
        message = '后端接口请求超时'
      }
      if (message.includes('Request failed with status code')) {
        const code = message.substr(message.length - 3)
        message = '后端接口' + code + '异常'
      }

      showFailToast(message || '后端接口未知异常')
      return Promise.reject(error)
    }
  }
)

/**
 * @description GET
 */
const GET = <T = any>({ url, params }: requestType): Promise<T> => {
  return service({
    url,
    method: 'GET',
    params
  } as AxiosRequestConfig)
}

/**
 * @description POST
 */
const POST = <T = any>({ url, params }: requestType): Promise<T> => {
  return service({
    url,
    method: 'POST',
    data: params
  } as AxiosRequestConfig)
}
/**
 * @description PUT
 */
const PUT = <T = any>({ url, params }: requestType): Promise<T> => {
  return service({
    url,
    method: 'PUT',
    data: params
  } as AxiosRequestConfig)
}

/**
 * @description DELETE
 */
const DELETE = <T = any>({ url, params }: requestType): Promise<T> => {
  return service({
    url,
    method: 'delete',
    data: params
  } as AxiosRequestConfig)
}

/**
 * @description PATCH
 */
const PATCH = <T = any>({ url, params }: requestType): Promise<T> => {
  return new Promise((resolve, reject) => {
    service
      .put(url, params)
      .then((res: any) => {
        if (res && res.status === 200) {
          resolve(res)
        }
      })
      .catch((error: any) => {
        reject(error)
      })
  })
}
export { GET, POST, PUT, DELETE, PATCH }

export default service
